package com.wanghlme.bookstore.handler;

import com.wanghlme.bookstore.exception.CustomException;
import com.wanghlme.bookstore.exception.CustomResult;
import com.wanghlme.bookstore.exception.ErrorInfoEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理
 *
 * @author WangHailong
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public CustomResult customExceptionHandler(HttpServletRequest request, CustomException e) {
        logger.error("发生业务异常！原因：{}", e.getErrorMsg());
        return CustomResult.failure(e.getErrorCode(), e.getErrorMsg());
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public CustomResult exceptionHandler(HttpServletRequest request, NullPointerException e) {
        logger.error("发生空指针异常！原因：{}", e.toString());
        return CustomResult.failure(ErrorInfoEnum.BODY_NOT_MATCH);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CustomResult exceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("未知异常！原因：{}", e.toString());
        return CustomResult.failure(ErrorInfoEnum.INTERNAL_SERVER_ERROR);
    }


}
